package com.updateNew;

import javax.swing.*;

import org.come.test.Main;
import org.come.until.CutButtonImage;

import com.tool.btn.RoleCaoZuoBtn;
import com.tool.tcp.GetTcpPath;
import com.tool.tcp.SpriteFactory;
import com.tool.tcpimg.UIUtils;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

//测试类
public class MyQdModeJFrame extends JPanel{
	//创建窗体
	private static JFrame myJFrame = new JFrame("登录方式");
	//    private JRadioButton rb1,rb2;
	private static JLabel labtext1,labtext2,labtext3;
	private static RoleCaoZuoBtn sureGive, deleteGive;
	static int i = 1;
	public static String version = "";
	private String txt = "红木UI";
	//构造方法初始化背景图片
	private Image image;

	public MyQdModeJFrame(){
		version = getVersion();
		updateStyle(txt);
		//获取图片
		Image im = new ImageIcon("img/bjt.PNG").getImage();
		//设置窗体大小
		myJFrame.setSize(350,560);
		MyQdModeJFrame myJPanel = new MyQdModeJFrame(im);
		sureGive = new RoleCaoZuoBtn("inkImg/old/1/yjdkdl.png", 1, "", 3345, UIUtils.COLOR_BTNPUTONG);
		sureGive.setBounds(100, 350, 68, 56);
		myJPanel.add(sureGive);
		deleteGive = new RoleCaoZuoBtn("inkImg/old/1/ptdl.png", 1, "", 3346, UIUtils.COLOR_BTNPUTONG);
		deleteGive.setBounds(200, 350, 68, 56);
		myJPanel.add(deleteGive);
//      //system.out.println(txt);
		//单选按钮
		JLabel label1=new JLabel("选择界面风格：");
		JRadioButton rb1=new JRadioButton("红木UI",true);    //创建JRadioButton对象
		JRadioButton rb2=new JRadioButton("水墨UI");    //创建JRadioButton对象
		label1.setFont(new Font("楷体",Font.BOLD,16));    //修改字体样式
		ButtonGroup group=new ButtonGroup();
//        添加JRadioButton到ButtonGroup中
		group.add(rb1);
		group.add(rb2);
		myJPanel.add(label1);
		myJPanel.add(rb1);
		myJPanel.add(rb2);

		myJFrame.setUndecorated(true);
		myJFrame.add(myJPanel);
		myJFrame.setLocationRelativeTo(null);
		myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		myJFrame.setVisible(true);


		rb1.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				txt=((JRadioButton)e.getSource()).getText();
				updateStyle(txt);
			}
		});

		rb2.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				txt=((JRadioButton)e.getSource()).getText();
				updateStyle(txt);
			}
		});
	}




	public MyQdModeJFrame(Image image){
		this.image = image;
	}



	/**
	 * 说明：根据指定URL将文件下载到指定目标位置
	 *
	 * @param urlPath
	 *            下载路径
	 * @param downloadDir
	 *            文件存放目录
	 * @return 返回下载文件
	 */
	@SuppressWarnings("finally")
	public static File downloadFile2(String urlPath, String downloadDir) {
		new MyQdModeJFrame();
		File file = null;
		try {
			// 统一资源
			URL url = new URL(urlPath);
			// 连接类的父类，抽象类
			URLConnection urlConnection = url.openConnection();
			// http的连接类
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			//设置超时
			httpURLConnection.setConnectTimeout(1000*5);
			//设置请求方式，默认是GET
			httpURLConnection.setRequestMethod("GET");
			// 设置字符编码
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			// 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
			httpURLConnection.connect();
			// 文件大小
			int fileLength = httpURLConnection.getContentLength();

			// 控制台打印文件大小
//          //system.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");
			labtext1.setBounds(150, 440, 280, 30);
			labtext1.setText("您要下载的文件大小为："+(fileLength / (1024 * 1024)) + "MB");
			labtext2.setBounds(65, 460, 280, 20);
			labtext2.setText("资源下载中");
			labtext3.setBounds(655, 457, 280, 20);
			labtext3.setText("当前版本："+version);
			// 建立链接从请求中获取数据
			URLConnection con = url.openConnection();

			// 使用 try-with-resources 确保资源正确关闭
			try (BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
				 OutputStream out = new FileOutputStream(file)) {
				// 指定文件名称(有需求可以自定义)
				String fileFullName = "xyWjGame-0.1.exe";
				// 指定存放位置(有需求可以自定义)
				String path = downloadDir + File.separatorChar + fileFullName;
				file = new File(path);
				// 校验文件夹目录是否存在，不存在就创建一个目录
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}

				int size = 0;
				int len = 0;
				byte[] buf = new byte[2048];
				while ((size = bin.read(buf)) != -1) {
					len += size;
					out.write(buf, 0, size);
					// 控制台打印文件下载的百分比情况
//                  //system.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
					labtext1.setBounds(150, 440, 280, 30);
					i = len * 100 / fileLength;
					if(i>70) {
						labtext1.setText("正在解压资源......");
						labtext2.setBounds(65, 460, 280, 20);
						labtext2.setText("资源处理中");
						labtext3.setBounds(655, 457, 280, 20);
						labtext3.setText("当前版本："+version);
					}else {
						labtext1.setText("下载进度："+(len * 100 / fileLength + 25) + "%\n");
						labtext2.setBounds(65, 460, 280, 20);
						labtext2.setText("资源下载中");
						labtext3.setBounds(655, 457, 280, 20);
						labtext3.setText("当前版本："+version);
					}
				}
			}
//          //system.out.println("游戏更新成功！正在启动请稍后！！！");
			labtext1.setText("游戏更新成功！正在启动请稍后！！！");
			labtext2.setBounds(65, 460, 280, 20);
			labtext2.setText("正在启动");
			labtext3.setBounds(655, 457, 280, 20);
			labtext3.setText("当前版本："+version);
			Thread.sleep(1500);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//          //system.out.println("文件下载失败！");
			labtext1.setText("文件下载失败！");
		} finally {
			return file;
		}

	}




	//重写paintComponent方法
	@Override
	public void paintComponent(Graphics g) {
		//调用父类paintComponent方法绘制其他组件
		super.paintComponent(g);
		//绘制背景图片，大小为窗体大小
		g.drawImage(image, 0, 0,getWidth(),getHeight(), null);
	}


	public String getVersion() {
		String inOld = "";
		String ur = System.getProperty("user.dir");
		String filePathOld = ur+"/resource/TXT/ifupdate.txt";

		// 使用 try-with-resources 确保资源正确关闭
		try (FileInputStream finOld = new FileInputStream(filePathOld);
			 InputStreamReader readerOld = new InputStreamReader(finOld);
			 BufferedReader buffReaderOld = new BufferedReader(readerOld)) {

			String strTmpOld = "";
			while((strTmpOld = buffReaderOld.readLine())!=null){
//              //system.out.println(strTmpOld);
				inOld = strTmpOld;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inOld;
	}


	public static String ggt(String[] s) {
		getSingle();
		MyIsif.ifs="D";
		try {
			Main.main(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
		myJFrame.dispose();
		return null;
	}



	public static String ggtd(String[] s) {
		//调试打开
		MyIsif.ifs="DK";
		getMultiple();
		try {
			tab.Main.main(s);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		myJFrame.dispose();
		return null;
	}


	public static void getMultiple() {
		String in = "";
		String ur = System.getProperty("user.dir");
		String filePath = ur+"/resource/other/StartUpMode.txt";

		// 使用 try-with-resources 确保资源正确关闭
		try (FileInputStream fin = new FileInputStream(filePath);
			 InputStreamReader reader = new InputStreamReader(fin);
			 BufferedReader buffReader = new BufferedReader(reader)) {

			String strTmp = "";
			while((strTmp = buffReader.readLine())!=null){
//              //system.out.println(strTmp);
				in = strTmp;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		File file = null;
		// 使用 try-with-resources 确保资源正确关闭
		try (FileWriter fw = new FileWriter(file = new File(filePath))) {
			if (!file.exists()) {
				file.createNewFile();
			}
			fw.write("Multiple");//向文件中写内容
			fw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	public static void getSingle() {
		String in = "";
		String ur = System.getProperty("user.dir");
		String filePath = ur+"/resource/other/StartUpMode.txt";

		// 使用 try-with-resources 确保资源正确关闭
		try (FileInputStream fin = new FileInputStream(filePath);
			 InputStreamReader reader = new InputStreamReader(fin);
			 BufferedReader buffReader = new BufferedReader(reader)) {

			String strTmp = "";
			while((strTmp = buffReader.readLine())!=null){
//              //system.out.println(strTmp);
				in = strTmp;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		File file = null;
		// 使用 try-with-resources 确保资源正确关闭
		try (FileWriter fw = new FileWriter(file = new File(filePath))) {
			if (!file.exists()) {
				file.createNewFile();
			}
			fw.write("Single");//向文件中写内容
			fw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//        SpriteFactory.Prepare(GetTcpPath.skillla());
	}

	public static void updateStyle(String txt) {
		String in = "";
		String ur = System.getProperty("user.dir");
		String filePath = ur+"/resource/other/style.txt";

		// 使用 try-with-resources 确保资源正确关闭
		try (FileInputStream fin = new FileInputStream(filePath);
			 InputStreamReader reader = new InputStreamReader(fin);
			 BufferedReader buffReader = new BufferedReader(reader)) {

			String strTmp = "";
			while((strTmp = buffReader.readLine())!=null){
				in = strTmp;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		File file = null;
		// 使用 try-with-resources 确保资源正确关闭
		try (FileWriter fw = new FileWriter(file = new File(filePath))) {
			if (!file.exists()) {
				file.createNewFile();
			}
			fw.write(txt);//向文件中写内容
			MyIsif.style = txt;
			fw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
